<?php

/**
 *  客户跟进记录
 */

namespace app\admin\service;

use app\admin\model\FollowRecords as ModelFollowRecords;
use app\admin\model\Order as ModelOrder;
use app\admin\model\WholesalOrder as ModelWholesalOrder;
use app\admin\model\Customer as ModelCustomer;
use app\facade\Basic;
use think\facade\Db;
use app\common\service\CompleteNotificationService;

class FollowRecords extends BaseService
{


    /**
     *   获取枚举
    */
    public function getEnum($param)
    {
       $modelSeller = new ModelFollowRecords();
       $result = $modelSeller->getFieldEnum($param['field']);
        return Basic::data(0,'ok',$result);
    }

    /**
     *  获取订单号
    */
    public function getOrderList($param) {

        $where[] = ['is_del','=',0];
        if (!empty($param['order_no'])) {
            $where[] = ['order_no', 'like', '%' . $param['order_no'] . '%'];
        }

        if (!empty($param['customer_id'])) {
            $where[] = ['user_id', '=', $param['customer_id']];
        }

        switch ($param['order_type']) {
            case 'order':
                $order = ModelOrder::where($where)
                    ->field("id,user_id,order_no,total_amount,create_time,'order' as order_type")
                    ->order('id','desc')
                    ->where('order_category','=','order')
                    ->paginate([
                        'list_rows'=> $param['pageSize'],
                        'var_page' => 'pageIndex',
                    ]);
                break;
            case 'wholesale':
                $order = ModelWholesalOrder::where($where)
                    ->field("id,user_id,order_no,total_amount,create_time,'wholesale' as order_type")
                    ->where('order_category','=','wholesal')
                    ->order('id','desc')
                    ->paginate([
                        'list_rows'=> $param['pageSize'],
                        'var_page' => 'pageIndex',
                    ]);
                break;
            default:
                return Basic::data(1,'订单 order_type 错误');
        }

        $data = $order->toArray();


        return Basic::paginator(0, 'ok', $data);

    }


    /**
     * 获取机型列表
     */
    public function getList($param)
    {

        $where[] = ['f.is_del', '=',0];

        if (!empty($param['customer_id'])) {
            $where[] = ['f.customer_id', '=',$param['customer_id']];
        }

        if (!empty($param['follow_method'])) {
            $where[] = ['f.follow_method', '=',$param['follow_method']];
        }

        if (!empty($param['order_type'])) {
            $where[] = ['f.order_type', '=',$param['order_type']];
        }

        if (!empty($param['follow_business'])) {
            $where[] = ['f.follow_business', '=',$param['follow_business']];
        }

        if (!empty($param['start_date']) && !empty($param['end_date'])) {
            $where[] = ['f.follow_time','between', [$param['start_date'], $param['end_date']]];
        }

        if(!empty($param['order_no']) && empty($param['order_type'])){
            return Basic::data(1,'订单号搜索必需选择订单类型');
        }

        $model = Db::table('db_follow_records')
            ->alias('f')
            ->leftJoin('db_operator o', 'f.creator = o.id')
            ->leftJoin('db_customer c', 'f.customer_id = c.id')
            ->leftJoin('db_order od', 'f.order_id = od.id');
        if (!empty($param['order_no'])) {
            $where[] = ['od.order_no', '=', $param['order_no']];
        }
        $result = $model
            ->where($where)
            ->field([
                'f.id',
                'f.customer_id',
                'f.follow_method',
                'f.follow_time',
                'f.follow_business',
                'f.order_id',
                'f.order_type',
                'f.follow_content',
                'f.create_time',
                'f.creator',
                'f.update_time',
                'o.cname as creator_name',
                'c.cusname as customer_name',
                'od.order_no',
                'od.order_category as order_type'
])
            ->paginate([
                'page' => $param['pageIndex'], // 当前页码
                'list_rows' => $param['pageSize'], // 每页记录数
            ]);

        return Basic::paginator(0, 'ok', $result->toArray());
    }


    /**
     * save
     */
    public function save($param)
    {


        $data = $param;
        $data['create_time'] = date('Y-m-d H:i:s',time());
        $data['follow_time'] = $param['follow_time'];

        if( empty($param['follow_business']) ) {
            unset($data['follow_business']);
        }

        $result = ModelFollowRecords::create($data);
        if ($result) {

            /* 更新最后跟进时间 */
            ModelCustomer::where('id', $data['customer_id'])->update(['last_followtime' => $param['follow_time']]);

            /* 记录日志 */
            $this->logger->logOperation($result->id, 'FollowRecords', '添加客户跟进记录', '添加客户跟进记录');

            /* 发送通知 */
            $customer = ModelCustomer::where('id', $data['customer_id'])->find();
            $notificationService = new CompleteNotificationService();
            $partnerArr = $customer->partner ? array_filter(explode(',', $customer->partner)) : [];
            $recipients = array_merge([$customer->owner], $partnerArr);
            $notificationService->send('customer_follow_records_created', array_merge($customer->toArray(), ['follow_content' => $param['follow_content']]), $recipients);

            return Basic::data(0, '保存成功');
        } else {
            return Basic::data(1, '保存失败');
        }
    }


    /**
     *  修改机型
     */
    public function update($param)
    {

        $result = ModelFollowRecords::where('id',$param['id'])->where('is_del','=',0)->find();

        if ( empty($result) ) {
            return Basic::data(1, 'ID 错误');
        }



        $result->customer_id = $param['customer_id'];
        $result->follow_method = $param['follow_method'];
        $result->follow_time = $param['follow_time'];

        if( !empty($param['follow_business']) ) {
            $result->follow_business = $param['follow_business'];
        } else {
            unset($result->follow_business);
        }

        $result->order_id = $param['order_id'];
        $result->order_type = $param['order_type'];
        $result->follow_content = $param['follow_content'];
        $result->update_time = date('Y-m-d H:i:s',time());

        if ($result->save()) {

            /* 更新最后跟进时间 */
            ModelCustomer::where('id',$result->customer_id)->update(['last_followtime'=>$param['follow_time']]);

            $this->logger->logOperation($result->id, 'FollowRecords', '修改', '修改客户跟进记录');
            return Basic::data(0, '修改成功');
        } else {
            return Basic::data(1, '修改失败');
        }
    }


    /**
     *  获取详情
    */
    public function detail($param)
    {
        $result = ModelFollowRecords::with([
            'creator_name'=>function($query){
                return $query->field('id,cname');
            },'customer_name'=>function($query){
                return $query->field('id,cusname');
            }])
            ->where('id','=',$param['id'])
            ->where('is_del','=',0)
            ->field('id,customer_id,follow_method,follow_time,follow_business,order_id,order_type,follow_content,create_time,creator,update_time')
            ->find();


        if ( !$result ) {
            return Basic::data(1, '未找到');
        }

        $data = $result->toArray();

        /* 创建人 */
        if(isset($data['creator_name'])) {
            $data['creator_name'] = $data['creator_name']['cname'];
        } else {
            $data['creator_name'] = '';
        }

        /* 客户 */
        if(isset($data['customer_name'])) {
            $data['customer_name'] = $data['customer_name']['cusname'];
        } else {
            $data['customer_name'] = '';
        }

        /* 获取订单信息 */
        $data['order_no'] = $this->getOrderItem($data['order_id'],$data['order_type']);


        if ( $result ) {
            return Basic::data(0, 'ok', $data);
        } else {
            return Basic::data(1, '获取失败');
        }
    }

    /**
     * 获取订单信
     */
    public function getOrderItem($order_id,$order_type) {
        switch ($order_type) {
            case 'order':
                $order_no = ModelOrder::where('id','=',$order_id)->value('order_no');
                break;
            case 'wholesale':
                $order_no = ModelWholesalOrder::where('id','=',$order_id)->value('order_no');
                break;
            default:
                $order_no = '';
        }

        return $order_no;
    }

    /**
     *   删除机型
    */
    public function delete($param)
    {
        $result = ModelFollowRecords::where('id','in',$param['ids'])->where('is_del','=',0)->select();
        if(!$result) {
            return Basic::data(1, '未找到');
        }

        if ( $result ) {
            $result = ModelFollowRecords::where('id','in',$param['ids'])->where('is_del','=',0)->update([
                'update_time' => date('Y-m-d H:i:s',time()),
                'is_del' => time()
            ]);

            if ( $result ) {
                $this->logger->logOperation($param['ids'], 'FollowRecords', '删除客户跟进记录', '删除客户跟进记录');
                return Basic::data(0, '删除成功');
            } else {
                return Basic::data(1, '删除失败');
            }

        } else {
            return Basic::data(1, '删除失败');
        }
    }
}
